package com.gsx.controller;

import com.gsx.entity.Product;
import com.gsx.dao.ProductDao;
import org.apache.lucene.util.QueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Optional;

@RestController
public class ProductController {
    @Autowired
    private ProductDao productDao;

    //查询所有
    @GetMapping("/listItem")
    public Iterable<Product> listItem(){
        //根据id 升序
        Iterable<Product> all = productDao.findAll(Sort.by("id").ascending());

        return all;
    }

    //spring data jpa的insert与update都调用同一个方法save，
    //如果带有主键id（如果启用了乐观锁，那么还有version字段），那么就是更新，否则就是新增
    //插入100条记录
    @GetMapping("/insert")
    public void insert() {
        for (int i = 100; i < 200; i++) {
            Product product = new Product();
            product.setId(i);
            product.setTitle("HUAWEI K"+i);
            product.setCategory("手机");
            product.setPrice(2000.0 + 10 * i);
            product.setImages("https://www.baidu.com/");
            productDao.save(product);
        }
    }

    //根据id查询
    @GetMapping("/findById")
    public Optional<Product> findById(){
        Optional<Product> product = productDao.findById(99L);
        return product;
    }

//    @GetMapping("/findByCategory")
//    public Optional<com.gsx.entity.Product> findByCategory(){
//        productDao.f
//    }

    //删除全部
    @GetMapping("/deleteAll")
    public void deleteAll(){
        productDao.deleteAll();
    }

    @GetMapping("/delete")
    public void delete() {
        Product product = new Product();
        product.setId(99);
        productDao.delete(product);
    }

    //根据title查询
    @GetMapping("/findByTitile")
    public List<Product> findByTitile(){
        String title = "HUAWEI K20";
        List<Product> list = productDao.findByTitle(title);
        return list;
    }

    //查询价格在price1和price2之间的
    //根据title查询
    @GetMapping("/findByPriceBetween")
    public List<Product> findByPriceBetween(){
        Double price1 = 2020D;
        Double price2 = 2050D;
        List<Product> priceBetween = productDao.findByPriceBetween(price1, price2);
        return priceBetween;
    }

    //分页查询
    @GetMapping("/findByPrice")
    public Page<Product> findByPrice(){
        String category = "笔记本电脑";
        Pageable pageable= PageRequest.of(0,5);
        Page<Product> page = productDao.findAllByCategoryOrderById(category, pageable);
        return page;
    }
}
